package com.jiankangjin.transsystem.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jiankangjin.httpclient.HttpClient;
import com.jiankangjin.trading.dao.IChannelDao;
import com.jiankangjin.trading.dao.IOrderDataDao;
import com.jiankangjin.trading.dao.IPaymentDataDao;
import com.jiankangjin.trading.entity.OrderDataEntity;
import com.jiankangjin.transsystem.common.Constant;

/**
 * 自动退款
 * 在网页上点击退款，搜索数据库中的测试数据，自动全额退款。
 */
@Controller
public class AutoRefundController {
	private static final Log log = LogFactory.getLog(AutoRefundController.class);
	
	@Autowired
	IPaymentDataDao paymentDataDao;
	
	@Autowired
	IOrderDataDao orderDataDao;
	
	@Autowired
	private IChannelDao channelDao;
	
	/**
	 * 将全部测试数据退款
	 */
    @RequestMapping(value = "/auto_refund", method = RequestMethod.POST)
    @ResponseBody
	public String autoRefund(
			HttpServletResponse response,
            @RequestParam(required = false) String token
            ) {
    	StringBuilder sb = new StringBuilder();
    	response.setCharacterEncoding("utf8");
    	if (!"password".equals(token)) {
    		sb.append("口令错误，请谨慎操作!!");
			return sb.toString();
		}
    	try {
    		OrderDataEntity orderExp = new OrderDataEntity();
        	orderExp.setPayStat(Constant.PAY_STAT_CODE_SUCCESS);
        	List<OrderDataEntity> orderList = new ArrayList<OrderDataEntity>();
        	orderList = orderDataDao.listByEntity(orderExp);
        	List<OrderDataEntity> orderList1 = new ArrayList<>();
        	for (OrderDataEntity orderDataEntity : orderList) {
        		if (!"1002".equals(orderDataEntity.getRefundStat())) {
        			orderList1.add(orderDataEntity);
				}
			}
        	orderList = orderList1;
        	if (orderList != null) {
        		sb.append("找到已支付的订单"+orderList.size()+"条\n");
        		for (int i = 0; i < orderList.size(); i++) {
        			log.info("处理第"+i+"条订单"+orderList.get(i).getId()+":");
        			sb.append("处理第"+i+"条订单"+orderList.get(i).getId()+":\n");
        			Map<String, Object> paramsC = new HashMap<String, Object>();
        			paramsC.put("module_id", "system");
        			paramsC.put("version", "v0.0.1");
        			paramsC.put("sign", "issign");
        			paramsC.put("order_id", orderList.get(i).getId());
        			paramsC.put("refund_fee", orderList.get(i).getOrdAmt());
        			paramsC.put("comment", "refund");
					Map<String, Object> createRefundMap = HttpClient.getInstance().doPOSTgetHashMap("/transSystem/create_refund", paramsC);
					sb.append("\t申请退款返回："+createRefundMap+"\n");
        			if ("0000".equals(createRefundMap.get("resp_status"))) {
        				Map<String, Object> paramsA = new HashMap<String, Object>();
            			paramsA.put("module_id", "system");
            			paramsA.put("version", "v0.0.1");
            			paramsA.put("order_id", orderList.get(i).getId());
            			paramsA.put("refund_fee", orderList.get(i).getOrdAmt());
            			paramsA.put("comment", "refund");
            			paramsA.put("sign", "issign");
            			paramsA.put("operator_id", "20141111111111111-1110018jYgCW9O");
            			paramsA.put("operator_name", "系统批处理");
    					Map<String, Object> allowRefundMap = HttpClient.getInstance().doPOSTgetHashMap("/transSystem/allow_refund", paramsA);
    					sb.append("\t退款复核返回："+allowRefundMap+"\n");
					}
//        			PaymentDataEntity payEntity = new PaymentDataEntity();
//                	payEntity.setOrdSysId(orderList.get(i).getId());
//                	payEntity.setPayStat(Constant.PAY_STAT_CODE_SUCCESS);
//                	List<PaymentDataEntity> payList = new ArrayList<PaymentDataEntity>();
//                	payList = paymentDataDao.listByEntity(payEntity);
//                	Map<String, Object> params = new HashMap<String, Object>();
//                	ChannelEntity channel = null;
//                	if (payList != null) {
//                		sb.append("\t此订单有已支付记录"+payList.size()+"条\n");
//            			for (PaymentDataEntity pay: payList) {
//            				channel = channelDao.selectByPrimaryKey(pay.getPayChnl());
//                			String path = "http://" + channel.getProjectUrl() + ":"
//                					+ channel.getProjectPort() + "/" + channel.getProjectName()
//                					+ "/refund";
//                			sb.append("\t"+pay.getId()+"处理开始:"+path+"\n");
//                			params.put("channel_fee_type", channel.getChannelFeeType());
//                			params.put("version", channel.getMethodVersion());
//                			params.put("pay_ssn_id", pay.getId());
//                			params.put("order_id", pay.getOrdSysId());
//                			params.put("total_fee", "1");
//                			params.put("pay_chnl_seq", pay.getPayChnlSeq());
//                			params.put("refund_fee", pay.getOrdAmt());
//                			params.put("currency", pay.getOrdCry());
//                			params.put("expand_json", "");
//                			params.put("sign", "transSystem_autoRefund_doRoute_sign");
//                			Map<String, Object> refundMap = HttpClient.getInstance().doPOSTgetHashMap(path, params);
//							if (refundMap != null
//									&& "0000".equals(refundMap
//											.get("resp_status"))
//									&& "1002".equals((String) refundMap
//											.get("refund_status"))) {
//								sb.append("\t\t" + "退款成功\n");
//							} else {
//								sb.append("\t\t" + "退款失败\n");
//							}
//						}
//            		} else {
//            			sb.append("订单"+orderList.get(i).getId()+"没有支付记录\n");
//            		}
				}
			}
		} catch (Exception e) {
		}
		return sb.toString();
	}
}
